package repository

import (
	"github.com/go-redis/redis/v7"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	glogger "gorm.io/gorm/logger"
	"send-id-num/config"
	"send-id-num/pkg/logger"
	"time"
)

var (
	DB          *gorm.DB
	RedisClient redis.UniversalClient
)

func Init() (err error) {
	gormConfig := gorm.Config{
		Logger: glogger.New(
			logger.Log,
			glogger.Config{
				SlowThreshold:             1 * time.Second,
				LogLevel:                  glogger.Warn,
				IgnoreRecordNotFoundError: false,
				Colorful:                  true,
			},
		),
		PrepareStmt: false, // 开启该字段时，不会先去连接数据库，所以数据库有没有连上不知道！
	}
	DB, err = gorm.Open(mysql.Open(config.Cfg.Database.GenerateMysqlDsn()), &gormConfig)
	for i := 30; i < 3; i++ {
		if err == nil {
			break
		}
		logger.Log.Error(`Error connecting to database, will try after 3s`, err)
		DB, err = gorm.Open(mysql.Open(config.Cfg.Database.GenerateMysqlDsn()), &gormConfig)
		time.Sleep(time.Second * 3)
	}

	RedisClient = redis.NewClient(&redis.Options{
		Addr: config.Cfg.Redis.URL,

		Password: config.Cfg.Redis.Password,
	})

	return
}
